#include <zephyr.h>
#include <shell/shell.h>
#include <shell/shell_uart.h>
#include <logging/log.h>

#include <version.h>
#include <stdlib.h>
#include <gpio.h>
#include <board.h>
#include <pwm.h>
#include <led.h>
#include "nrf52.h"
#include "nrf.h"
#include <sensor.h>

#include <adc.h>
#include <hal/nrf_saadc.h>

#define ADC_DEVICE_NAME		DT_ADC_0_NAME
#define ADC_RESOLUTION		10
#define ADC_GAIN		ADC_GAIN_1_6
#define ADC_REFERENCE		ADC_REF_INTERNAL
#define ADC_ACQUISITION_TIME	ADC_ACQ_TIME(ADC_ACQ_TIME_MICROSECONDS, 10)
#define ADC_1ST_CHANNEL_ID	0
#define ADC_1ST_CHANNEL_INPUT	NRF_SAADC_INPUT_AIN1

#define BUFFER_SIZE  1
static s16_t m_sample_buffer[BUFFER_SIZE];

static const struct adc_channel_cfg m_1st_channel_cfg = {
	.gain             = ADC_GAIN,
	.reference        = ADC_REFERENCE,
	.acquisition_time = ADC_ACQUISITION_TIME,
	.channel_id       = ADC_1ST_CHANNEL_ID,
#if defined(CONFIG_ADC_CONFIGURABLE_INPUTS)
	.input_positive   = ADC_1ST_CHANNEL_INPUT,
#endif
};

static struct device *adc_dev;

static struct device *init_adc(void)
{
	int ret;
	struct device *adc_dev = device_get_binding(ADC_DEVICE_NAME);
	if(adc_dev == NULL){
		printf("Cannot get ADC device");
	}

	ret = adc_channel_setup(adc_dev, &m_1st_channel_cfg);
	if(ret != 0){
		printf("Setting up of the first channel failed with code %d", ret);
	}

	(void)memset(m_sample_buffer, 0, sizeof(m_sample_buffer));

	return adc_dev;
}

LOG_MODULE_REGISTER(app);

static int cmd_dht(void)
{
	struct sensor_value temp, humidity;
	struct device *dev = device_get_binding("DHT11"); //根据Device name获取驱动
	printf("dev %p name %s\n", dev, dev->config->name);
	sensor_sample_fetch(dev);								  //从dh11读取数据
	sensor_channel_get(dev, SENSOR_CHAN_AMBIENT_TEMP, &temp); //读取温度
	sensor_channel_get(dev, SENSOR_CHAN_HUMIDITY, &humidity); //读取湿度

	printf("temp: %d.%06d; humidity: %d.%06d\n",
		   temp.val1, temp.val2, humidity.val1, humidity.val2);
	return 0;
}

static int cmd_adc(void)
{
	adc_dev = init_adc();
	if(adc_dev){
		const struct adc_sequence sequence = {
			.channels    = BIT(ADC_1ST_CHANNEL_ID),
			.buffer      = m_sample_buffer,
			.buffer_size = sizeof(m_sample_buffer),
			.resolution  = ADC_RESOLUTION,
		};

		int ret;
		ret = adc_read(adc_dev, &sequence);
		if(ret == 0){
			printf("Read bat %d\n", m_sample_buffer[0]);
		}
	}
}


void main(void)
{
	float x = 1.35;
	printf("Frank printf %f\n", x);

	while(1){
		//cmd_dht();
		//cmd_adc();
		k_sleep(1000);
	}
}
